package com.order.service.impl.loadbalance;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Description: 负载均衡算法
 * @Author: mingtian
 * @CreateDate: 2020/1/10 16:28
 * @Version: 1.0
 */
@Component
public class RotationLoadBalancer implements LoadBalance {

    private Logger LOGGER = LoggerFactory.getLogger(getClass());

    private AtomicInteger atomicInteger = new AtomicInteger(Integer.MAX_VALUE - 1);

    @Override
    public ServiceInstance getServiceInstance(List<ServiceInstance> serviceInstanceList) {
        if (atomicInteger.get() == Integer.MAX_VALUE) {
            atomicInteger = new AtomicInteger(-1);
        }
        int index = atomicInteger.incrementAndGet() % serviceInstanceList.size();
        LOGGER.info("After:count:{}", atomicInteger.get());
        return serviceInstanceList.get(index);
    }
}